#ifndef COMTHREAD_H
#define COMTHREAD_H

#include <QThread>
#include <QObject>
#include <QSerialPort>
#include <QTimer>

#define WAIT_STU_OUT  0
#define WAIT_STU_WAIT 1
#define WAIT_STU_DATA 2

#define USB_PAGE_NULL		0x00
#define USB_PAGE_OUT		0x01
#define USB_PAGE_LINK		0x5A
#define USB_PAGE_BREAK		0xA5
#define USB_PAGE_SYNC		0x55
#define USB_PAGE_REPEAT 	0xAA
#define USB_PAGE_BUSY		0xBB
#define USB_PAGE_ERROR		0xFF
#define USB_PAGE_READ_MTSN	0x11
#define USB_PAGE_READ_DATA	0x12
#define USB_PAGE_BURN_MTSN	0x21
#define USB_PAGE_BURN_DATA	0x22

const QString USB_PAGE_HEAD = "-mtsn ";
const QString USB_PAGE_ERR_FPC = "FPC";

class ComThread : public QThread
{
    Q_OBJECT
public:
    explicit ComThread(QObject *parent = nullptr);

    QStringList GetSerialAvailable();
    bool InitSerial(QString portname);
    void CloseSerial();

    void RecvTime_Init(long DataSize);
    void SendSerial_LinkCmd_Link();
    void SendSerial_LinkCmd_Wait();
    void SendSerial_LinkCmd_Break();
    void SendSerial_LinkCmd_Repeat();
    void RecvSerial_LinkCmd_Repeat();

    bool RecvData_TimeOut(QByteArray data);

signals:
    void UpdateSerialData(QByteArray data);

public slots:
    void SerialPort_Read_Start();
    void ReceviceSerialData();
    void RespTimer_TimeOut();
    void WaitTimer_TimeStart();
    void WaitTimer_TimeStop();
    bool WaitTimer_TimeActive();
    void WaitTimer_TimeOut();
    void SendSerialData(QByteArray data);
    void SendSerial_MtsnCmd_SendCode(QByteArray code, uint16_t addr);
    void SendSerial_MtsnCmd_RecvCode(QByteArray code, uint16_t addr);
    void SendSerial_MtsnCmd_SendData(QByteArray data, uint16_t addr);
    void SendSerial_MtsnCmd_RecvData(QByteArray data, uint16_t addr);

private:
    int RespStu;
    QSerialPort *mSerial;
    QTimer *RecvTimer;
    QTimer *RecvTimer_Dlbox;
    long RecvTime;
    long RecvTimeOut;
    QTimer *RespTimer;
    QTimer *RespTimer_Dlbox;
    QTimer *WaitTimer;
    QTimer *WaitTimer_Dlbox;
    QByteArray LastCmd;
};

#endif // COMTHREAD_H
